<template>
  <div class="home">
    <div class="map">
      <div id="olmap">
        <!-- 四周渐变边框 -->
        <div id="border" />
        <!-- 四周渐变边框 -->

        <!-- 顶部大屏标题 -->
        <div id="header-container">数据引接</div>
        <!-- 顶部大屏标题 -->

        <!-- 右上角区域和目标信息  -->
        <div id="info">
          <emphasis-area-and-target
            @monitore="monitore"
            @monitoreArea="monitoreArea"
            @delete="deleArea"
            @drawArea="drawPolgon"
          />
        </div>
        <!-- 右上角区域和目标信息  -->

        <!-- 右下角舰机信息 -->
        <div id="custom-popup" :style="{ right: offsetRight }">
          <equipmentInfoPopup :info-column="infoColumn" :info-data="markerData" />
        </div>
        <!-- 右下角舰机信息 -->

        <!-- 自定义地图工具 -->
        <div id="tool-bar">
          <a-tooltip title="标注区域" placement="left">
            <img :src="areaSignImg" alt="标注区域" @click="drawArea" />
          </a-tooltip>
          <!-- <a-tooltip title="标注目标" placement="left">
            <img :src="targetSignImg" alt="标注目标" @click="signTarget">
          </a-tooltip> -->
          <a-tooltip title="返回" placement="left">
            <img :src="returnImg" alt="返回" @click="() => (recentModel = 'home')" />
          </a-tooltip>
        </div>
        <!-- 自定义地图工具 -->

        <!-- 中间筛选按钮 -->
        <div id="map-feature_filter">
          <map-featrue-filter ref="mapFeatrueFilterRef" @handle-change="handleChange" />
        </div>
        <!-- 中间筛选按钮 -->

        <!-- 左侧信息 -->
        <div id="left">
          <div class="event-alarm">
            <box-header>
              <event-alarm :recentModel="recentModel" />
            </box-header>
          </div>
          <!-- 首页默认数据 -->
          <div v-if="recentModel === 'home'" class="air-situation">
            <box-header title="舰机信息">
              <info-table
                class="air-situation_table"
                :need-tabs="true"
                :table-data="equipmentInfoTableData"
                :table-column="equipmentInfoTableColumn"
                @tab-change="tabChange"
              />
            </box-header>
          </div>
          <div v-if="recentModel === 'home'" class="air-situation">
            <box-header title="北斗数据">
              <info-table
                class="air-situation_table"
                :table-data="beidou_situation_mock_data"
                :table-column="beidou_situation_mock_column"
              />
            </box-header>
          </div>
          <!-- 首页默认数据 -->

          <!-- 区域信息 -->
          <div v-if="recentModel === 'area'" class="air-situation">
            <box-header title="区域信息">
              <area-info :area-info-data="areaInfoData" />
            </box-header>
          </div>
          <div v-if="recentModel === 'area'" class="air-situation">
            <box-header title="区域内机舰信息">
              <area-equipment-info />
            </box-header>
          </div>
          <!-- 区域信息 -->

          <!-- 重点目标信息 -->
          <div v-if="recentModel === 'target'" class="air-situation">
            <box-header title="目标信息">
              <target-info :target-data="markerData" />
            </box-header>
          </div>
          <div v-show="recentModel === 'target'" class="air-situation">
            <box-header title="目标监控信息">
              <target-monitoring-info :target-monitoring-info-data="markerData" />
            </box-header>
          </div>
          <!-- 重点目标信息 -->
        </div>
        <!-- 左侧信息 -->

        <div id="footer" />
      </div>
    </div>
  </div>
  <add-highlights-and-focus
    ref="addHighlightsAndFocusRef"
    :key-type="currentMouseAction"
    @confirm-add="confirmAdd"
    @cancel-add="cancelAdd"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
  import { message } from 'ant-design-vue'
  import MapUtils from '@/utils/olMap/track'
  import * as turf from '@turf/turf'
  import { endLoop, genUseData } from '@/utils'
  import { useEquipmentInfo } from '@/store/modules/equipmentInfo'
  import { mapData } from '@/store/modules/mapData'
  import { storeToRefs } from 'pinia'

  import equipmentInfoPopup from './components/EquipmentInfoPopup/index'
  import AddHighlightsAndFocus from './components/AddHighlightsAndFocus/index.vue'
  import EmphasisAreaAndTarget from './components/EmphasisAreaAndTarget/index.vue'
  import BoxHeader from './components/BoxHeader/index'
  import EventAlarm from './components/EventAlarm/index.vue'
  import MapFeatrueFilter, { type FilterData } from './components/MapFeatrueFilter/index.vue'
  import InfoTable from './components/InfoTable/index.vue'
  import AreaInfo from './components/AreaInfo/index.vue'
  import AreaEquipmentInfo from './components/AreaEquipmentInfo/index.vue'
  import TargetInfo from './components/TargetInfo/index.vue'
  import TargetMonitoringInfo from './components/TargetMonitoringInfo/index.vue'

  import { infoColumn } from './components/EquipmentInfoPopup/indexConfig'

  import {
    air_situation_mock_column,
    sea_situation_mock_column,
    beidou_situation_mock_data,
    beidou_situation_mock_column
  } from './mock'

  import areaSignImg from '@/assets/images/layout/标注区域.png'
  import returnImg from '@/assets/images/layout/返回.png'

  let interval: any
  const mapDatas = mapData()
  const map = ref<any>(null)
  const markerData = ref<Record<string, any>>()
  const markerFeature = ref<Record<string, any>>()
  const offsetRight = ref<string>('-50vw')
  const addHighlightsAndFocusRef = ref()
  const currentMouseAction = ref<'area' | 'target' | ''>('area') // 当前鼠标动作
  const mapFeatrueFilterRef = ref()
  const watchId = ref('')
  const air_situation_data = ref<Record<string, any>[]>([])
  const sea_situation_data = ref<Record<string, any>[]>([])
  const equipmentInfoTableData = ref<Record<string, any>[]>()
  const equipmentInfoTableColumn = ref<any>(air_situation_mock_column)
  const areaInfoData = reactive<any>({}) // 区域信息 - 面积polygon
  const maxLength = ref<number>(1)

  const $equipmentInfo = useEquipmentInfo()
  const recentModel = ref<'home' | 'area' | 'target'>('home')
  const mapTool = new MapUtils()
  const mapOption = {
    target: 'olmap',
    center: [125.1508, 29.561],
    zoom: 6,
    minZoom: 3,
    maxZoom: 19
  }

  const drawArea = () /* 添加重点区域 */ => {
    currentMouseAction.value = 'area'
    mapTool.drawArea('Polygon')

    mapTool.draw.on('drawend', (evt) => {
      const areaDrawedPolygonData = evt.target.sketchLineCoords_
      addHighlightsAndFocusRef.value.extraProperties = areaDrawedPolygonData
      addTargetAndAreaInfoDirectly(areaDrawedPolygonData)
    })
  }

  const signTarget = () /* 标记重点目标 */ => {
    if (currentMouseAction.value === 'target') {
      // 判断当前点击舰机是否已添加
      const res: any = endLoop($equipmentInfo.targetInfo, (item) => {
        if (markerFeature.value && item.extraProperties.id === markerFeature.value.id) {
          message.warning('当前舰机已添加')
          return true
        }
      })

      if (markerFeature.value) {
        // 重点目标为空（初次添加）
        if ($equipmentInfo.targetInfo.length === 0) {
          addHighlightsAndFocusRef.value.extraProperties = markerFeature.value
          addTargetAndAreaInfoDirectly(markerFeature.value)
        } else {
          res.catch(() => {
            addHighlightsAndFocusRef.value.extraProperties = markerFeature.value
            addTargetAndAreaInfoDirectly(markerFeature.value)
          })
        }
      }
    }
  }

  const addTargetAndAreaInfoDirectly = (extraProperties?: Record<string, any>) => {
    currentMouseAction.value === 'area' &&
      $equipmentInfo.addInfo('area', {
        batchNumber: `区域${maxLength.value}`,
        id: Math.random(),
        extraProperties: { polygon: extraProperties }
      })
    currentMouseAction.value === 'target' &&
      $equipmentInfo.addInfo('target', {
        batchNumber: extraProperties?.properties?.batchNumber,
        id: Math.random(),
        extraProperties
      })
    maxLength.value += 1
  }

  const confirmAdd = () /* 确认添加后移除前一个画的 polygon */ => {
    // mapTool.handleRemoveLayer('drawLayer');
  }
  const cancelAdd = () /* 确认添加后移除前一个画的 polygon */ => {
    mapTool.handleRemoveLayer('drawLayer')
    mapTool.handleRemoveLayer('drawLayer')
  }

  const planeFeatureClick = () /* 飞机要素点击事件 */ => {
    return new Promise((resolve) => {
      map.value.on('click', (evt) => {
        const features = map.value.getFeaturesAtPixel(evt.pixel)

        // 处理点击的舰机
        if (features.length > 0 && features[0].getProperties().id?.includes('air')) {
          const { properties } = features[0].getProperties()

          markerFeature.value = features[0].getProperties()

          currentMouseAction.value = 'target'

          signTarget() // 点击飞机直接添加为重点目标

          resolve(true)

          markerData.value = {
            ...properties,
            id: features[0].getProperties().id
          }

          offsetRight.value = '10px'
        } else {
          if (recentModel.value === 'target') {
            return
          }

          markerFeature.value = {}
          markerData.value = {}
          currentMouseAction.value = ''

          offsetRight.value = '-50vw'
        }
      })
    })
  }

  const backHome = () => {
    if (interval) {
      clearInterval(interval)
    }
    mapTool.backToHome(mapOption)
  }

  const monitore = (record: Record<string, any>) /* 表格监控按钮 */ => {
    recentModel.value = 'target'

    watchId.value = record.extraProperties.id

    markerData.value = {
      ...record.extraProperties.properties,
      id: record.extraProperties.id
    }
    offsetRight.value = '10px'
  }

  const handleChange = (value: FilterData) /* 中间筛选事件，返回三个参数 */ => {
    console.log('%c [  ]-136', 'font-size:13px; background:#efe982; color:#ffffc6;', value)
  }

  const monitoreArea = (record: Record<string, any>) /* 表格监控按钮 */ => {
    const polygon = turf.polygon([record.extraProperties.polygon])
    const acreage = (turf.area(polygon) / 1000000).toFixed(2)

    areaInfoData.acreage = acreage
    areaInfoData.weather = '晴/8°'
    areaInfoData.planeNumber = 1
    areaInfoData.shipNumber = 0

    recentModel.value = 'area'
    mapTool.moveToArea(record.keyName)
  }

  const getAirAndSeaInfoFromStore = () /* 从 stroe 获取舰机信息 */ => {
    const $mapData = mapData()
    const { planeInfo } = storeToRefs($mapData)

    Object.keys(planeInfo.value).forEach((key) => {
      if (planeInfo.value[key].linkData === 'airplaneData') {
        air_situation_data.value.push(planeInfo.value[key])
      }
      if (planeInfo.value[key].linkData === 'warshipData') {
        sea_situation_data.value.push(planeInfo.value[key])
      }
    })

    equipmentInfoTableData.value = air_situation_data.value
  }
  getAirAndSeaInfoFromStore()

  const tabChange = (value: string) /* 舰机信息表格切换 */ => {
    const tabChangeMap = {
      air: () => {
        equipmentInfoTableData.value = air_situation_data.value
        equipmentInfoTableColumn.value = air_situation_mock_column
      },
      sea: () => {
        equipmentInfoTableData.value = sea_situation_data.value
        equipmentInfoTableColumn.value = sea_situation_mock_column
      }
    }

    tabChangeMap[value]()
  }

  const setPlaneInfo = (id: string, pos: any, desiredTrack: string, properties: any) => {
    mapDatas.setplaneInfo(id, {
      ...properties,
      position: pos,
      speed: Math.floor(properties.speed / 2),
      height: Math.floor(properties.height / 2),
      desiredTrack
    })
  }

  const drawPolgon = (id: string, points: number[]) => {
    setTimeout(() => {
      mapTool.drawPolygon(id, points)
    }, 500)
  }

  const deleArea = (id: string) => {
    const layer = mapTool.drawLayers[id] ? mapTool.drawLayers[id] : mapTool.drawLayers.temp
    mapTool.map.removeLayer(layer)
  }

  onMounted(() => {
    map.value = mapTool.initMap(mapOption)

    const useData = genUseData()

    useData.forEach((item) => {
      mapTool.initFlightAnimation(item.data, 10, setPlaneInfo) // 10的速度对应当前距离下100秒
    })

    planeFeatureClick()
  })

  onUnmounted(() => {
    if (interval) {
      clearInterval(interval)
    }
    mapTool.onDestory()
  })

  // 监听当前模式，
  watch(
    () => recentModel.value,
    (newVal) => {
      if (interval) {
        clearInterval(interval)
      }

      switch (newVal) {
        case 'home':
          backHome()
          break
        case 'area':
          break
        case 'target':
          if (watchId.value) {
            // 自动飞
            mapTool.map.getView().setZoom(8)
            interval = setInterval(() => {
              mapTool.moveToPoint(mapDatas.getplaneInfo(watchId.value).position)
            }, 10)
          }
          break
        default:
          break
      }
    }
  )
</script>

<style lang="less" scoped>
  .button {
    width: 48px;
    height: 60px;
    font-size: 20px;
    color: #6093c3;
  }

  #olmap {
    width: 100%;
    height: calc(100vh - 125px);
    border: 1px solid #96d1db;
    position: relative;
    overflow: hidden;

    #border {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 3;
      height: 100%;
      width: 100%;
      pointer-events: none;
      box-shadow: inset 0 0 60px 0 rgba(105, 152, 188, 0.7), inset 0 0 120px 0 rgba(105, 152, 188, 0.1);
    }

    #header-container {
      position: absolute;
      top: 0px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 9;
      background: url('../../assets/images/layout/顶栏.png') no-repeat center/80%;
      min-height: 70px;
      min-width: 1300px;
      font-size: 27px;
      font-weight: 600;
      color: #fff;
      text-shadow: 0px 0px 10px #0065c4;
      text-align: center;
    }

    #custom-popup {
      position: absolute;
      top: 320px;
      z-index: 9;
      width: fit-content;
      transition: all 0.3s;
    }

    #tool-bar {
      position: absolute;
      top: 80px;
      right: 436px;
      z-index: 9;
      display: flex;
      flex-direction: column;
      row-gap: 10px;

      img {
        width: 48px;
        height: 48px;

        &:hover {
          filter: drop-shadow(0px 0px 0 #24f6f0);
        }
      }
    }

    #map-feature_filter {
      position: absolute;
      top: 80px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 9;
    }

    #info {
      position: absolute;
      top: 36px;
      right: 20px;
      z-index: 9;
    }

    #left {
      position: absolute;
      top: 36px;
      left: 20px;
      z-index: 9;
      display: flex;
      flex-direction: column;
      row-gap: 10px;

      .event-alarm {
      }

      .air-situation {
        .air-situation_table {
          width: 380px;
        }
      }
    }

    #footer {
      position: absolute;
      bottom: 0px;
      left: 0px;
      z-index: 9;
      min-height: 40px;
      width: 100%;
      background: linear-gradient(90deg, rgba(14, 116, 215, 0.8), rgba(0, 92, 255, 0), rgba(14, 116, 215, 0.8));
    }

    :deep(.ol-viewport) {
      .ol-overlaycontainer-stopevent {
        z-index: 10 !important;

        .ol-zoom {
          top: 80px;
          left: 440px;
          box-shadow: 0px 0px 3px 0px rgba(96, 147, 195, 0.5);
          border-radius: 4px;

          & > button {
            .button();
          }

          .ol-zoom-in {
            border-radius: 4px 4px 0 0;
          }

          .ol-zoom-out {
            border-radius: 0 0 4px 4px;
          }
        }

        .custom-mouse-position {
          position: absolute;
          bottom: 8px;
          left: 220px;
          font-size: 14px;
          color: #fff;
        }

        .ol-scale-line {
          background: unset !important;

          .ol-scale-line-inner {
            font-size: 12px;
            color: #fff;
            border-color: #fff;
            border-width: 3px;
            height: 10px;
            line-height: 0px;
          }
        }
      }
    }
  }
</style>
